// SysConfigController.java
package com.nb.controller;

import com.mybatisflex.core.paginate.Page;
import com.nb.dto.ConfigQueryDTO;
import com.nb.entity.SysConfig;
import com.nb.entity.SysConfigHistory;
import com.nb.result.Result;
import com.nb.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/config")
public class SysConfigController {

    private static final Logger logger = LoggerFactory.getLogger(SysConfigController.class);

    @Autowired
    private ISysConfigService configService;

    /**
     * 获取所有系统配置
     */
    @GetMapping("/all")
    public Result getAllConfigs() {
        logger.info("获取所有系统配置");
        List<SysConfig> configs = configService.getAllConfigs();
        return Result.success(configs);
    }

    /**
     * 修改系统配置
     */
    @PutMapping("/update")
    public Result updateConfig(@RequestBody SysConfig config) {
        logger.info("修改系统配置: {}", config);
        boolean result = configService.updateConfig(config);
        if (result) {
            // 更新后刷新缓存
            configService.refreshCache();
            return Result.success("配置更新成功");
        }
        return Result.error("配置更新失败");
    }

    /**
     * 刷新配置缓存
     */
    @PostMapping("/refreshCache")
    public Result refreshCache() {
        logger.info("刷新配置缓存");
        configService.refreshCache();
        return Result.success("缓存刷新成功");
    }

    @GetMapping("/public")
    public Result getPublicConfigs() {
        List<SysConfig> publicConfigs = configService.getPublicConfigs();
        // 转换为Map格式（key-value）方便前端使用
        Map<String, String> configMap = publicConfigs.stream()
                .collect(Collectors.toMap(
                        SysConfig::getConfigKey,
                        SysConfig::getConfigValue
                ));
        return Result.success(configMap);
    }

    /**
     * 查询配置变更历史
     */
    @GetMapping("/history")
    public Result getConfigHistory(
            // 移除分页参数，如需分页可保留但不影响全量查询
            @RequestParam(required = false) Integer configId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        // 调用全量查询方法
        List<SysConfigHistory> historyList = configService.getHistoryByPage(configId, startTime, endTime);
        return Result.success(historyList);  // 直接返回列表
    }

}